package api

import (
	"github.com/gin-gonic/gin"
)

// SetupRoutes 设置API路由
func (h *Handler) SetupRoutes(router *gin.Engine) {
	// API版本分组
	v1 := router.Group("/api/v1")
	v1.Use(RequireJSONContentType()) // 应用Content-Type验证中间件
	{
		// Flow相关路由
		flows := v1.Group("/flows")
		{
			flows.POST("", h.CreateFlow)                            // 创建Flow
			flows.GET("", h.ListFlows)                              // 获取所有Flow
			flows.GET("/:id", h.GetFlow)                            // 获取单个Flow
			flows.PUT("/:id", h.UpdateFlow)                         // 更新Flow
			flows.DELETE("/:id", h.DeleteFlow)                      // 删除Flow
			flows.POST("/:id/execute", h.ExecuteFlow)               // 手动执行Flow
			flows.GET("/:id/executions", h.GetFlowExecutionHistory) // 获取Flow执行历史
		}

		// Node相关路由
		nodes := v1.Group("/nodes")
		{
			nodes.POST("", h.CreateNode)                    // 创建Node
			nodes.GET("", h.ListNodes)                      // 获取所有Node (支持flow_id查询参数)
			nodes.GET("/:id", h.GetNode)                    // 获取单个Node
			nodes.PUT("/:id", h.UpdateNode)                 // 更新Node
			nodes.DELETE("/:id", h.DeleteNode)              // 删除Node
			nodes.GET("/:id/script", h.GetNodeScript)       // 获取节点脚本
			nodes.POST("/:id/script", h.SaveNodeScript)     // 保存节点脚本
		}

		// Action相关路由
		actions := v1.Group("/actions")
		{
			actions.POST("", h.CreateAction)       // 创建Action
			actions.GET("", h.ListActions)         // 获取所有Action (支持node_id查询参数)
			actions.GET("/:id", h.GetAction)       // 获取单个Action
			actions.PUT("/:id", h.UpdateAction)    // 更新Action
			actions.DELETE("/:id", h.DeleteAction) // 删除Action
		}

		// 执行相关路由
		executions := v1.Group("/executions")
		{
			executions.GET("", h.GetAllFlowExecutions)       // 获取所有执行记录
		executions.GET("/:id", h.GetFlowExecutionStatus) // 获取执行状态
		executions.GET("/:id/nodes", h.GetExecutionNodes) // 获取执行的节点状态
		}

		// 通知配置路由
		notifications := v1.Group("/notifications")
		{
			notifications.POST("", h.CreateNotificationConfig) // 创建通知配置
			notifications.GET("", h.GetNotificationConfigs)    // 获取通知配置
		}
	}

	// 健康检查
	router.GET("/health", func(c *gin.Context) {
		c.JSON(200, gin.H{"status": "healthy", "service": "Alfred CICD"})
	})

	// API文档说明
	router.GET("/api", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"service": "Alfred CICD",
			"version": "1.0.0",
			"endpoints": gin.H{
				"flows":         "/api/v1/flows",
				"nodes":         "/api/v1/nodes",
				"actions":       "/api/v1/actions",
				"executions":    "/api/v1/executions",
				"notifications": "/api/v1/notifications",
				"webhook":       "/webhook/gitlab",
				"health":        "/health",
			},
		})
	})
}
